import React, { useCallback, useEffect, useState } from 'react';
import { Space, Table, Tag } from 'antd';
import type { TableProps } from 'antd';
import http from '../../../api/http'
import type { FormProps } from 'antd';
import { Button, Popconfirm, Form, Input, Drawer } from 'antd';
import {
  RedoOutlined, SearchOutlined, PlusSquareOutlined, SettingFilled, DeleteOutlined
} from '@ant-design/icons';
import type { PopconfirmProps } from 'antd';
import { message, Radio } from 'antd';

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}


const Guan: React.FC = () => {
  // 定义数据
  const [list, setList] = useState([])
  const [total, setTotal] = useState(10)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [title, setTitle] = useState('')
  const [tag, setTag] = useState('')
  const [flag, setFlag] = useState(false)

  const fetchList = async () => {
    const params: {
      page: number,
      pageSize: number,
      keyword: string,
      tag: string
    } = {
      page, pageSize
    }
    if (title) params.keyword = title
    if (tag) params.tag = tag
    const res = await http.get('/article/list', { params })
    console.log(res, '列表')
    if (res.data.rows) {
      setList(res.data.rows)
      setTotal(res.data.count)
    }
  }

  useEffect(() => {
    fetchList()
  }, [page, pageSize, title, tag])

  // 分页
  const ochange = (currentPage: number, currentPageSize: number) => {
    setPage(currentPage)
    setPageSize(currentPageSize)
  }

  // 搜索
  const onFinish: FormProps['onFinish'] = (values) => {
    setTitle(values.title)
    setTag(values.tag)
  };
  // 重置
  const [formchong] = Form.useForm();
  const chong = () => {
    setTitle('')
    setTag('')
    formchong.resetFields()
  }
  // 删除
  const confirm: PopconfirmProps['onConfirm'] = useCallback((e) => {
    console.log(e);
    message.success('删除成功');
    fetchList()
  }, [list])

  // 新增+编辑

  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();

  // 编辑
  const handleEdit = (record) => {
    setOpen(true)
    form.setFieldsValue(record)
    setFlag(true)
  }

  // record
  const showDrawer = async () => {
    setOpen(true);
    setFlag(false)
    const res = await http.post('/article', {
      title: string,
      content: string,
      tagList: ["新增"],
      categoryList: ["新增测试"],
      authorId: 47529555
    })
    console.log(res, '新增')
    fetchList()
    form.resetFields('')
  };

  const onClose = () => {
    setOpen(false);
  };


  const columns: TableProps<DataType>['columns'] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '阅读数量',
      dataIndex: 'viewCount',
      key: 'viewCount',
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
    },

    {
      title: 'Tags',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.name.length > 5 ? 'geekblue' : 'green';
            return (
              <Tag color={color} key={tag.name}>
                {tag.name.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button>查看</Button>
          <Button onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm
            title="是否删除数据"
            description="您真的要删除吗?"
            onConfirm={() => confirm(record)}
            okText="Yes"
            cancelText="No"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  const handleOk = () => {
    setOpen(false)
    message.success('成功');
  }

  return (
    <div>
      {/* 表单 */}
      <Form
        name="basic"
        layout='inline'
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 1600, padding: '10px' }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
        form={formchong}
      >
        <Form.Item
          label="用户名"
          name="title"
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="用户状态"
          name="tag"
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="性别"
          name="sex"
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="昵称"
          name="name"
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="手机号"
          name="phone"
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="邮箱"
          name="email"
        >
          <Input />
        </Form.Item>


        <Form.Item label={null}>
          <Button type="primary" onClick={() => chong()}>
            <RedoOutlined />重置
          </Button>
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            <SearchOutlined />搜索
          </Button>
        </Form.Item>
      </Form>
      <hr />
      {/* 新增按钮+ 批量删除 */}
      <div style={{ display: 'flex', justifyContent: 'end' }}>
        <Button onClick={showDrawer}><PlusSquareOutlined />新增</Button>
        <Button><DeleteOutlined />批量删除</Button>
        <Button><RedoOutlined />刷新</Button>
        <Button><SettingFilled />列设置</Button>
      </div>

      {/* 表格 */}
      <Table<DataType>
        columns={columns}
        dataSource={list}
        pagination={{
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `总共 ${total} 条`,
          onChange: ochange
        }}
      />
      <Drawer
        title={flag == 1 ? '编辑' : '新增'}
        closable={{ 'aria-label': 'Close Button' }}
        onClose={onClose}
        open={open}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          autoComplete="off"
          form={form}
        >


          <Form.Item
            label="用户名"
            name="title"
            rules={[{ required: true, message: '输入用户名!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="用户状态"
            name="tags"
            rules={[{ required: true, message: '输入状态!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="性别"
            name="sex"
          >
            <Radio.Group
              options={[
                { value: 1, label: '男' },
                { value: 0, label: '女' },
              ]}
            />
          </Form.Item>

          <Form.Item
            label="昵称"
            name="viewCount"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="updatedAt"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="邮箱"
            name="content"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="用户角色"
            name="content"
          >
            <Input />
          </Form.Item>

          <Form.Item label={null}>
            <Button type='dashed' onClick={() => handleOk()}>
              确认
            </Button>
            <Button>
              取消
            </Button>
          </Form.Item>

        </Form>

      </Drawer>
    </div>
  )
}

export default Guan;